package com.daocao.hua.adapter;

import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.daocao.hua.activity.OpinionActivity;
import com.daocao.hua.R;
import com.daocao.hua.activity.WechatChatActivity;
import com.daocao.hua.util.PreferenceUtils;
import com.daocao.hua.constant.Const;
import com.daocao.hua.interfaces.OnRecyclerViewListener;
import com.daocao.hua.model.ContentDetailModel;
import com.daocao.hua.util.ToastUtil;
import com.daocao.hua.util.Util;
import com.daocao.hua.view.Dialog;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;

import java.util.List;


/**
 * SOS明细
 * Created by MasterDong on 16/4/12.
 */

public class HelpCenterAdapter extends RecyclerView.Adapter implements StickyRecyclerHeadersAdapter<RecyclerView.ViewHolder>, View.OnClickListener {


    private OnRecyclerViewListener onRecyclerViewListener;
    private final int TYPE_FIRST = 100;
    private View mViewHeader;

    private String mWeixinName;
    private String mPhoneNum;

    public void setOnRecyclerViewListener(OnRecyclerViewListener onRecyclerViewListener) {
        this.onRecyclerViewListener = onRecyclerViewListener;
    }

    private Context mContext;
    private List<ContentDetailModel> list;

    public HelpCenterAdapter(Context context, List<ContentDetailModel> list) {
        this.list = list;
        this.mContext = context;

        mWeixinName = PreferenceUtils.getString(mContext.getApplicationContext(), Const.KEY.SERVICE_WEIXIN, "稻草时代");
        mPhoneNum = PreferenceUtils.getString(mContext.getApplicationContext(), Const.KEY.SERVICE_PHONE, "13827260730");
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        if (i == TYPE_FIRST) {
            return new HeaderViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.help_center_header, null));
        } else {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.help_items, null);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(lp);
            return new HelpViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int i) {
        if (i == 0) {
            HeaderViewHolder holder = (HeaderViewHolder) viewHolder;
            holder.btnPhone.setOnClickListener(this);
            holder.btnWeixin.setOnClickListener(this);
            holder.btnSuggestion.setOnClickListener(this);

        } else {
            HelpViewHolder holder = (HelpViewHolder) viewHolder;
            holder.position = i - 1;
            ContentDetailModel model = list.get(i - 1);
            holder.title.setText(model.getTitle());
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
        mViewHeader = LayoutInflater.from(parent.getContext()).inflate(R.layout.help_item_header, null);
        return new HelpHeaderViewHolder(mViewHeader);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        HelpHeaderViewHolder holder = (HelpHeaderViewHolder) viewHolder;
        if (position > 0) {
            ContentDetailModel model = list.get(position - 1);
            holder.type.setText(model.getType());
        }
    }

    @Override
    public long getHeaderId(int position) {
        //Log.d("test", "position: ------------" + position + ",getItem:" + getItemId(position));

      /*  if (position > 0 && list.get(position - 1).getType() != null) {
            return getSortType(position);
        } else {
            return -1;
        }*/
        if (position > 0 && list.get(position - 1).getType() != null) {
            return position;
        } else {
            return -1;
        }
    }


    //获取当前相同的类型
    public int getSortType(int position) {
        int sort = -1;
        int sum = 0;
        for (int i = 0; i < list.size() - 1; i++) {
           /* for (int j = i+1 ; j < list.size(); j++) {
                Log.d("TAg--i-->",list.get(i).getType());
                Log.d("TAg--j-->",list.get(j).getType());*/
            if (list.get(i).getType().equals(list.get(i + 1).getType())) {
                {
                    sum++;

                }
            } else {
                sum = 0;
            }

            Log.d("TAg-->sum", sum + "");
            Log.d("TAg-position", position + "");
        }

        if (position >= sum) {
            sort++;
        } else {
            return sort;
        }
        return sort;
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return TYPE_FIRST;
        }
        return super.getItemViewType(position);
    }

    /**
     * 添加数据
     *
     * @param list
     */
    public void addList(List<ContentDetailModel> list) {
        this.list.addAll(list);
    }

    public void clearList() {
        this.list.clear();
    }

    @Override
    public int getItemCount() {
        return list.size() + 1;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_weixin:
                //复制 稻草时代
//                ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
//                ClipData clipData = ClipData.newPlainText("Label", "稻草时代");
//                cm.setPrimaryClip(clipData);
//
//                showWeixinDialog();
                Util.startActivity(mContext, WechatChatActivity.class);
                break;
            case R.id.btn_phone:
                showPhoneDialog();
                break;
            case R.id.btn_suggestion:
                Util.startActivity(mContext, OpinionActivity.class);
                break;
        }
    }

    private void showWeixinDialog() {
        Dialog.showDefaultDialog(mContext, getString(R.string.tip), getString(R.string.copy_dob_weixin) + "“" + mWeixinName + "”公众号-关注", getString(R.string.cancel), getString(R.string.focus), true, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                try {
                    if (isWeixinAvailable(mContext)) {
                        // ComponentName（组件名称）是用来打开其他应用程序中的Activity或服务的
                        Intent intent = new Intent();
                        ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");// 报名该有activity

                        intent.setAction(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_LAUNCHER);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setComponent(cmp);

                        mContext.startActivity(intent);
                    } else {
                        ToastUtil.makeText(mContext, "您未安装微信", Toast.LENGTH_SHORT).show();
                    }
                } catch (ActivityNotFoundException e) {
                    ToastUtil.makeText(mContext, "您未安装微信", Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            public void cancel() {

            }
        });
    }

    private String getString(int id) {
        return mContext.getResources().getString(id);
    }

    private void showPhoneDialog() {
        Dialog.showDefaultDialog(mContext, getString(R.string.tip), getString(R.string.call_dob_phone) + mPhoneNum, getString(R.string.cancel), getString(R.string.dial), true, new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mPhoneNum));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }

            @Override
            public void cancel() {

            }
        });
    }

    public static boolean isWeixinAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }

        return false;
    }

    class HeaderViewHolder extends RecyclerView.ViewHolder {

        private final RelativeLayout btnWeixin;
        private final RelativeLayout btnPhone;
        private final RelativeLayout btnSuggestion;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            btnWeixin = (RelativeLayout) itemView.findViewById(R.id.btn_weixin);
            btnPhone = (RelativeLayout) itemView.findViewById(R.id.btn_phone);
            btnSuggestion = (RelativeLayout) itemView.findViewById(R.id.btn_suggestion);
        }
    }

    class HelpViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
        public View rootView;
        public TextView title;
        public int position;

        public HelpViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.title);

            rootView = itemView.findViewById(R.id.loan_record_item);
            rootView.setOnClickListener(this);
            rootView.setOnLongClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (null != onRecyclerViewListener) {
                onRecyclerViewListener.onItemClick(list, position);
            }
        }

        @Override
        public boolean onLongClick(View v) {
            if (null != onRecyclerViewListener) {
                return onRecyclerViewListener.onItemLongClick(list, position);
            }
            return false;
        }

    }

    class HelpHeaderViewHolder extends RecyclerView.ViewHolder {
        public TextView type;

        public HelpHeaderViewHolder(View itemView) {
            super(itemView);
            type = (TextView) itemView.findViewById(R.id.type);

        }

    }
}

